package com.cma.cmabackend.util;

import com.cma.cmabackend.entity.Equipment;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * &#064;description:  解析excel表格到设备类的列表
 */
public class EquipmentParser {
    static public List<Equipment> parseEquipment(MultipartFile file) throws IOException {
        List<Equipment> equipmentList = new ArrayList<>();
        Workbook workbook = WorkbookFactory.create(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);

        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);

            Equipment equipment = new Equipment();
            equipment.setEquipNo(getCellValue(row.getCell(0)));
            equipment.setName(getCellValue(row.getCell(1)));
            equipment.setLevel(getCellValue(row.getCell(2)));
            equipment.setScope(getCellValue(row.getCell(3)));
            String temp = getCellValue(row.getCell(4));
            if (temp == "") {
                equipment.setAddYear(null);
            }else {
                equipment.setAddYear(Double.valueOf(temp).intValue());
            }
            equipment.setTraceMethod(getCellValue(row.getCell(5)));
            equipment.setValidDate(getCellValue(row.getCell(6)));
            equipment.setSource(getCellValue(row.getCell(7)));

            equipmentList.add(equipment);
        }
        workbook.close();
        return equipmentList;
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        return switch (cell.getCellType()) {
            case STRING -> cell.getStringCellValue().trim();
            case NUMERIC -> String.valueOf(cell.getNumericCellValue());
            default -> "";
        };
    }
}
